/**
 * Created by felix on 2017/3/5.
 */
import React from 'react';
import moment from 'moment';
import { connect } from 'dva';
import _ from 'lodash';
import { Table, Button, Divider, Popconfirm } from 'antd';
import Editor from './edit';
import common from '../common.less';

function DeviceList({ deviceManage, baseData, dispatch }) {
    const { data, editorData } = deviceManage;
    const onRemoveData = ({...query}) => {
        const { id } = query;
        dispatch({
            type: 'deviceManage/removeData',
            selectId: id,
        });
    };
    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
        },
        {
            title: 'mac地址',
            dataIndex: 'macAddress',
        },
        {
            title: '绑定时间',
            dataIndex: 'bindTime',
            render: (t) => {
                return moment(t).format('YYYY-MM-DD HH:mm:ss');
            },
        },
        {
            title: '操作',
            render: (t, r) => {
                return (
                    <div>
                        <a onClick={onEditorData.bind(null, r)}>编辑</a>
                        <Divider type="vertical" />
                        <Popconfirm
                            title="您要删除码?"
                            okText="删除"
                            cancelText="取消"
                            onConfirm={onRemoveData.bind(null, r)}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </div>
                );
            },
        },
    ];
    const onEditorData = (data) => {
        dispatch({
            type: 'deviceManage/editorVisible',
            payload: { editorData: data },
        });
    };
    const editProps = {
        name: '设备数据',
        ns: 'deviceManage',
        isNew: _.isEmpty(editorData),
        dispatch,
    };
    return (
        <div className={common.normalWrap}>
            <div className={common.buttonWrap}>
                <Button type="primary" onClick={onEditorData.bind(null, {})}>添加设备</Button>
            </div>
            <div className={common.table}>
                <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={data}
                />
                <Editor {...{ baseData, ...deviceManage, ...editProps }}/>
            </div>
        </div>
    );
}

function mapStateToProps({ deviceManage, app: { baseData } }) {
    return { deviceManage, baseData };
}

export default connect(mapStateToProps)(DeviceList);
